package com.vcredit.creditcat.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.dubbo.config.annotation.Reference;
import com.vcredit.creditcat.api.IAppTokenManager;
import com.vcredit.creditcat.api.IAuthorizeManager;
import com.vcredit.creditcat.api.ICustManager;
import com.vcredit.creditcat.bean.Session;
import com.vcredit.creditcat.dto.AppLoginInfoDto;
import com.vcredit.creditcat.dto.AppLoginParamDto;
import com.vcredit.creditcat.enumtype.AccountTypeEnum;
import com.vcredit.creditcat.exception.AppTokenNullException;

public class AppTokenInterceptor extends HandlerInterceptorAdapter {
	
	public static final Logger LOG = LoggerFactory.getLogger(AppTokenInterceptor.class);

	@Reference(version = "1.0")
	private IAppTokenManager appTokenService;
	@Reference(version = "1.0")
	private ICustManager custService;
	@Reference(version = "1.0")
	private IAuthorizeManager authorizeManager;
	@Value("${open.sign}")
	private Boolean isSign;
	@Value("${project.env}")
	private String env;


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		LOG.info("------------拦截请求URL：" + request.getServletPath());
		String token = request.getHeader("accessToken");
		if (null == token) {
			token = request.getParameter("accessToken");
		}
		LOG.info("------------拦截请求accessToken：" + token);
		if (isSign && StringUtils.isBlank(token)) {
			throw new AppTokenNullException("token不能为null");
		}
		Long custId = 6681L;
		Long accountId = 6681L;
		String tokenStr =null;
		if (isSign) {
			custId = appTokenService.getCustIdFromToken(token);
			accountId = appTokenService.getAccountIdFromToken(token);
			String driverId = appTokenService.checkAppToken(token, custId, accountId);
			if (StringUtils.isNotBlank(driverId)) {
				//此token和用户最后一次登录token相同，主动做静默登录
				AppLoginParamDto loginParam = new AppLoginParamDto();
				loginParam.setLoginType(AccountTypeEnum.Auto.getCode().toString());
				loginParam.setDeviceId(driverId);
				AppLoginInfoDto loginInfoDto = authorizeManager.appLogin(loginParam,null,null);
				tokenStr = loginInfoDto.getAccessToken();
				response.setHeader("accessToken", tokenStr);
			}
		}else{
			custId = appTokenService.getCustIdFromToken(token);
			accountId = appTokenService.getAccountIdFromToken(token);
		}

		Session s = (Session) request.getSession().getAttribute("session");
		if (s == null || s.getCust() == null || s.getAccountId() == null
				|| (s.getCust() != null && !s.getCust().getCustId().equals(custId))) {
			s = new Session();
			s.setCust(custService.findById(custId));
			s.setAccountId(accountId);
			request.getSession().setAttribute("session", s);
		}

		return true;
	}
}
